<template>
    <view class="container">
        <!-- 左上角显示页码 -->
        <view class="page-number top-left">{{currentPage}}/{{totalPages}}</view>
        <view class="case" >
            <view v-for="(node, index) in nodes" :key="node.id" class="node" v-if="nodeIf"
                :style="{ top: node.top + 'rpx', left: node.left + 'rpx' }" @click="addNodeLine(index)"
                @touchstart="addNodeLine(index, $event)" @touchmove="addNodeLine(index, $event)"
                @touchend="addNodeLine(index)">
                <view v-if="index%2===0" class="nodeBg">
                    <image class="xiugai-icon" :src="node.img"   mode="aspectFit" @click.stop="playCardAudio(node.audio)"/>
                </view>
                <view v-else class="nodeBgLine">
                    <view class="nodeBgChildren" @click="playCardAudio(node.audio)">
                        {{node.name}}
                    </view>
                </view>
            </view>
            <view v-for="(line, k) in lines" :key="line.id" class="line" :style="{
              top: `${line.startY}rpx`,
              left: `${line.startX}rpx`,
              width: `${line.width}rpx`,
              height: `${line.height}rpx`,
              transform: `rotate(${line.angle}deg)`,
            }"></view>
        </view>
        <div class="page-buttons">
            <!-- 上一页按钮 -->
            <button @click="prevPage" class="page-button prev-button">上一页</button>
            <!-- 下一页按钮 -->
            <button @click="nextPage" :disabled="!isGameCompleted" class="page-button next-button">下一页</button>
        </div>
        <button @click="reset" class="page-button resetClass">重置 {{currentPage}}/{{totalPages}}</button>
    </view>
</template>

<script>
import {lxSelectGame,twoCompleteGame} from "../../../api/index"

// 全局音频管理器
class AudioManager {
  constructor() {
    this.audioContexts = new Map();
    this.initAudioContext();
    this.isPlaying = false; // 音频播放状态
    this.audioQueue = []; // 音频播放队列
    this.currentPlaying = null; // 当前正在播放的音频路径
  }
  
  initAudioContext() {
    // 创建音频上下文，提高初始化速度
    try {
      this.globalContext = uni.createInnerAudioContext();
      this.globalContext.obeyMuteSwitch = false; // 不遵循系统静音
    } catch (e) {
      console.error('初始化音频上下文失败:', e);
    }
  }
  
  // 预加载音频
  preloadAudio(audioPath) {
    if (!audioPath || this.audioContexts.has(audioPath)) return;
    
    const audioCtx = uni.createInnerAudioContext();
    audioCtx.src = audioPath;
    audioCtx.obeyMuteSwitch = false; // 不遵循系统静音
    audioCtx.autoplay = false;
    audioCtx.loop = false;
    
    // 预加载
    audioCtx.onCanplay(() => {
      console.log(`音频 ${audioPath} 预加载完成`);
    });
    
    // 监听音频播放结束事件
    audioCtx.onEnded(() => {
      this.isPlaying = false;
      this.currentPlaying = null;
      this.playNextInQueue();
    });
    
    // 监听音频错误事件
    audioCtx.onError((err) => {
      console.error('音频播放错误:', err);
      this.isPlaying = false;
      this.currentPlaying = null;
      this.playNextInQueue();
    });
    
    this.audioContexts.set(audioPath, audioCtx);
  }
  
  // 播放音频
  play(audioPath) {
    if (!audioPath) return;
    
    // 如果正在播放相同的音频，不重复播放
    if (this.currentPlaying === audioPath) {
      return;
    }
    
    // 如果有音频正在播放，将新的音频加入队列
    if (this.isPlaying) {
      // 停止当前播放的音频
      this.stopCurrent();
      // 清空队列
      this.audioQueue = [];
    }
    
    let audioCtx = this.audioContexts.get(audioPath);
    
    // 如果没有预加载，则立即创建并播放
    if (!audioCtx) {
      audioCtx = uni.createInnerAudioContext();
      audioCtx.src = audioPath;
      audioCtx.obeyMuteSwitch = false;
      audioCtx.autoplay = true;
      audioCtx.loop = false;
      
      // 设置音频结束和错误监听
      audioCtx.onEnded(() => {
        this.isPlaying = false;
        this.currentPlaying = null;
        this.playNextInQueue();
      });
      
      audioCtx.onError((err) => {
        console.error('音频播放错误:', err);
        this.isPlaying = false;
        this.currentPlaying = null;
        this.playNextInQueue();
      });
      
      this.audioContexts.set(audioPath, audioCtx);
      this.isPlaying = true;
      this.currentPlaying = audioPath;
      return;
    }
    
    // 停止当前播放并重新播放
    try {
      if (!audioCtx.paused) {
        audioCtx.stop();
      }
      // 重置音频位置到开始
      audioCtx.seek(0);
      audioCtx.play();
      this.isPlaying = true;
      this.currentPlaying = audioPath;
    } catch (e) {
      console.error('播放音频失败:', e);
      // 出错时创建新的音频实例
      const newAudioCtx = uni.createInnerAudioContext();
      newAudioCtx.src = audioPath;
      newAudioCtx.obeyMuteSwitch = false;
      newAudioCtx.autoplay = true;
      newAudioCtx.loop = false;
      
      // 设置音频结束和错误监听
      newAudioCtx.onEnded(() => {
        this.isPlaying = false;
        this.currentPlaying = null;
        this.playNextInQueue();
      });
      
      newAudioCtx.onError((err) => {
        console.error('音频播放错误:', err);
        this.isPlaying = false;
        this.currentPlaying = null;
        this.playNextInQueue();
      });
      
      this.audioContexts.set(audioPath, newAudioCtx);
      this.isPlaying = true;
      this.currentPlaying = audioPath;
    }
  }
  
  // 播放队列中的下一个音频
  playNextInQueue() {
    if (this.audioQueue.length > 0) {
      const nextAudio = this.audioQueue.shift();
      this.play(nextAudio);
    }
  }
  
  // 清理资源
  clear() {
    this.audioContexts.forEach(ctx => {
      ctx.stop();
      ctx.destroy();
    });
    this.audioContexts.clear();
    this.isPlaying = false;
    this.audioQueue = [];
    this.currentPlaying = null;
  }
  
  // 停止当前播放的音频
  stopCurrent() {
    if (this.isPlaying) {
      // 找到当前播放的音频并停止
      this.audioContexts.forEach(ctx => {
        if (!ctx.paused) {
          ctx.stop();
        }
      });
      this.isPlaying = false;
      this.currentPlaying = null;
      this.audioQueue = []; // 清空队列
    }
  }
}

export default {
    data() {
        return {
            clsCrsId:null,
            groupForm:{},
            nodeIf:false,
            nodes: [{
                    id: 1,
                    top: 30,
                    left: 50,
                    used: false,
                },
                {
                    id: 2,
                    top: 180,
                    left: 50,
                    used: false,
                },
                {
                    id: 3,
                    top: 30,
                    left: 250,
                    used: false,
                },
                {
                    id: 4,
                    top: 180,
                    left: 250,
                    used: false,
                },
                {
                    id: 5,
                    top: 30,
                    left: 450,
                    used: false,
                },
                {
                    id: 6,
                    top: 180,
                    left: 450,
                    used: false,
                },
            ],
            errorNo:0,
            statesNum:0,
            lines: [],
            lastClickedNode: null,
            lastEndNode: null,
            startX: null,
            startY: null,
            endX: null,
            endY: null,
            crsId:null,
            clsId:null,
            clsCrsId:null,
            gameId:null,
            currentPage: 1, // 当前页码
            totalPages: 0, // 总页数
            audioManager: new AudioManager() // 音频管理器实例
        };
    },
    computed: {
        isGameCompleted() {
            return this.statesNum >= 3; // 三组连线都成功才能完成游戏
        }
    },
    onLoad(e) {
        console.log(e,'2222')
        this.clsId=e.clsId
        this.crsId=e.crsId
        this.totalPages=e.Size
        this.clsCrsId =Number(e.id)
        this.$nextTick(function(){
            this.selectGameList()
        })
    },
    onUnload() {
        // 清理音频资源
        this.audioManager.clear();
    },
    methods: {
        //查询连线游戏
        selectGameList(){
            var jsonData = {
                clsCrsId:this.clsCrsId,
                crsId:this.crsId,
                pageNum: this.currentPage, // 使用当前页码
            };
            lxSelectGame(jsonData).then(response => {
            if (response.code === 0) {
                this.gameId= response.data.gameId
                this.nodeIf=true
                let mergedArray = this.nodes.map((obj1, index) => {
                  let obj2 = response.data.gameList[index] || {};
                  return { ...obj1, ...obj2 };
                });
                this.nodes = mergedArray
                
                // 预加载当前页的所有音频
                this.preloadCurrentPageAudios();
            }else{
                this.nodeIf=false
                uni.$u.toast(response.msg) 
            }
            }).catch(errors => {
            })
        },
        
        // 预加载当前页的所有音频
        preloadCurrentPageAudios() {
            this.nodes.forEach(node => {
                if (node.audio) {
                    this.audioManager.preloadAudio(node.audio);
                }
            });
        },
        
        addNodeLine(index,item) {
            if (!this.nodes[index].used && this.isValidNode(index)) {
                if (this.lastClickedNode !== null && (this.lastEndNode === null || index === this.lastEndNode)) {
                    this.drawLine(this.lastClickedNode, index,item);
                }
                this.lastClickedNode = index;
                if (index === this.lastEndNode) {
                    this.lastClickedNode = null;
                }
                if (index === this.lastEndNode) {
                    this.lastClickedNode = null;
                    this.lastEndNode = null;
                    this.nodes[index].used = true;
                }
            }
        },
        drawLine(startIndex, endIndex,item) {
            const startNode = this.nodes[startIndex];
            const endNode = this.nodes[endIndex];
            if (startIndex % 2 === 0) {
                this.startX = startNode.left + 70;
                this.startY = startNode.top + 100;
                this.endX = endNode.left + 50;
                this.endY = endNode.top + 0;
            }
            if (startIndex % 2 === 1) {
                this.startX = startNode.left + 70;
                this.startY = startNode.top + 0;
                this.endX = endNode.left + 50;
                this.endY = endNode.top + 100;
            }
            const dx = this.endX - this.startX;
            const dy = this.endY - this.startY;
            const length = Math.sqrt(dx * dx + dy * dy);
            const angle = Math.atan2(dy, dx) * (180 / Math.PI);
            this.lines.push({
                id: `${startIndex}-${endIndex}`,
                startX: this.startX,
                startY: this.startY,
                width: length,
                height: 2,
                angle: angle
            });
            this.lastEndNode = endIndex;
            if (startNode.biaoshi === endNode.biaoshi) {
                this.statesNum++;
                if(this.statesNum >= 3){
                    this.sumbPic()
                }
            }else{
                uni.$u.toast('连线错误请重新操作！');
                this.errorNo++
                this.reset()
            }
        },
        //播放音频 - 优化版本
        playCardAudio(audioPath) {
            if (!audioPath) return;
            
            // 先停止当前播放的音频
            this.audioManager.stopCurrent();
            
            // 再播放新的音频
            this.audioManager.play(audioPath);
        },
        sumbPic(){
            var jsonData = {
                clsId:this.clsId,
                clsCrsId:this.clsCrsId,
                crsId:this.crsId,
                tryNum:this.errorNo,
                gameId:Number(this.gameId)
            };
            let _this = this;
            twoCompleteGame(jsonData).then(response => {
                console.log(response)
                if (response.code === 0) {
                    // 停止当前播放的音频
                    this.audioManager.stopCurrent();
                    
                    uni.showModal({
                        title: '提示',
                        showCancel: false,
                        content: '恭喜你完成了！',
                        success: function(res) {
                            if (res.confirm) {
                                if (_this.currentPage < _this.totalPages) {
                                    _this.nextPage();
                                } else {
                                    uni.redirectTo({
                                        url:'/src/views/pageStudy/common/huodejifen/index?showButton=false'
                                    });
                                    _this.reset();
                                }
                            }
                        }
                    });
                }else{
                }
            })
        },
        isValidNode(index) {
            const currentIndex = index;
            if (this.lastClickedNode !== null) {
                const lastClickedIndex = this.lastClickedNode;
                if ((currentIndex % 2 === 1 && lastClickedIndex % 2 === 1) || (currentIndex % 2 === 0 &&
                        lastClickedIndex % 2 === 0)) {
                    this.lastClickedNode = currentIndex
                    return false;
                }
            }
            return true;
        },
        reset() {
            // 停止当前播放的音频
            this.audioManager.stopCurrent();
            
            this.nodes.forEach(node => {
                node.used = false;
            });
            this.lines = [];
            this.lastClickedNode = null;
            this.lastEndNode = null;
            this.statesNum = 0;
        },
        // 上一页
        prevPage() {
            // 停止当前播放的音频
            this.audioManager.stopCurrent();
            
            if (this.currentPage > 1) {
                this.currentPage--;
                this.selectGameList();
                this.reset();
            }
        },
        // 下一页
        nextPage() {
            // 停止当前播放的音频
            this.audioManager.stopCurrent();
            
            if (this.currentPage < this.totalPages && this.isGameCompleted) {
                this.currentPage++;
                this.selectGameList();
                this.reset();
            } else {
                if (!this.isGameCompleted) {
                    uni.$u.toast('请先完成三组连线！');
                } else {
                    uni.redirectTo({
                        url:'/src/views/pageStudy/common/huodejifen/index?showButton=false'
                    });
                    this.reset();
                }
            }
        }
    }
};
</script>
<style>
	page{
		overflow: hidden;
	}
</style>
<style lang="scss" scoped>

.resetClass{
    position: absolute;
    top: calc(50% + 80rpx); /* 调整重置按钮的位置 */
    margin-top: -25rpx;
    right: 5%; /* 调整右侧距离 */
    background: #246cdd;
    width: 80rpx; /* 与下一页按钮大小一致 */
    line-height: 35rpx;
    height: 35rpx;
    border: none;
    border-radius: 5rpx;
}
.container {
    position: relative;
    width: 100vw;
    height: 100vh;
    background-color: #f0f0f0;
    text-align: center;
}
.case {
    position: relative;
    width: 95%; /* 缩小连线循环部分所占宽度 */
    height: 100%;
    margin: 0 auto; /* 水平居中 */
}
.node {
    position: absolute;
    width: 140rpx;
    height: 100rpx;
    color: white;
    border-radius: 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    user-select: none;
}
.nodeBg{
    background-color: #fff; 
    width: 100%;
    height: 100%;
	overflow: hidden;
    border-radius: 20rpx;
    border:1px solid #808080;
}
.nodeBgLine{
    width: 100%;
    height: 100%;
    border-radius: 20rpx;
    background-color: #FFB607; 
    border:1px solid #FFB607;
    padding: 10rpx;
    padding-left: 20rpx;
    box-sizing: border-box;
}
.nodeBgChildren{
    width: 90%;
    height: 100%;
    justify-content: center;
    background: url('https://www.afbeijing.net/static_resources/assets/xiongmaotou.png') ;
    background-size:  100% 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-repeat: no-repeat;
}
.xiugai {
}
.xiugai-icon {
    width: 140rpx;
    height: 100rpx;
}
.line {
    position: absolute;
    background-color: #FFB607;
    transform-origin: 0 0;
}
button {
    background-color: red;
    color: white;
    width: 100%;
    height: 40rpx;
}
.page-number {
    position: absolute;
    font-size: 20rpx;
    color: #333;
}
.top-left {
    top: 20rpx;
    left: 20rpx;
}
.page-buttons {
    position: absolute;
    top: 50%;
    right: 5%; /* 调整右侧距离 */
    transform: translateY(-50%);
    display: flex;
    flex-direction: column;
    gap: 15rpx; /* 增加按钮间距 */
}
.page-button {
    width: 80rpx; 
    height: 35rpx;
    background-color: #FF8106;
    line-height: 35rpx;
    color: white;
	font-size: 14rpx;
    border: none;
    border-radius: 5rpx;
}
.prev-button {
}
.next-button {
}
</style>
    